﻿using System;
using System.Linq;
using Aluetjen.EmailService.Domain.Models.Message;

namespace Aluetjen.EmailService.Domain.Models.Pipeline
{
    public class Condition
    {
        public virtual MessageField Field { get; set; }
        public virtual string Regex { get; set; }

        public virtual bool IsSatisfiedFor(MailMessage message)
        {
            #region Parameter validation
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            #endregion

            string value = GetFieldValue(message);
            var match = System.Text.RegularExpressions.Regex.Match(value, Regex);

            return match.Success;
        }

        private string GetFieldValue(MailMessage message)
        {
            string value;

            try
            {
                switch (Field)
                {
                    case MessageField.Body:
                        value = message.Body;
                        break;
                    case MessageField.From:
                        value = message.From.Address;
                        break;
                    case MessageField.Subject:
                        value = message.Subject;
                        break;
                    case MessageField.To:
                        value = string.Join(";", message.To.Select(t => t.Address));
                        break;
                    default:
                        throw new InvalidOperationException(string.Format("Unknown field type {0}", Field));
                }
            }
            catch (NullReferenceException)
            {
                value = string.Empty;
            }

            return value ?? string.Empty;
        }
    }
}
